<template>
  <section class="app-container">
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="filters" @submit.native.prevent>
        <el-form-item>
          <el-input v-model="filters.name" placeholder="赛事名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="getTeam">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">报名</el-button>
        </el-form-item>
        <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      </el-form>
    </el-col>
    <!--列表-->
    <el-table :data="teamData" border highlight-current-row @selection-change="selsChange" style="width: 100%;height: 100%">
      <el-table-column type="selection" width="55">
      </el-table-column>
<!--      <el-table-column type="index" width="60">-->
<!--      </el-table-column>-->
      <el-table-column prop="title" label="赛事名称" min-width="120">
      </el-table-column>
      <el-table-column prop="projectId" label="项目编号" sortable min-width="100" >
      </el-table-column>
      <el-table-column prop="teamNo" label="团队编号" min-width="120">
    </el-table-column>
      <el-table-column prop="teamName" label="团队名称" min-width="120">
      </el-table-column>
      <el-table-column prop="enrollTime" sortable label="注册时间" min-width="120">
      </el-table-column>

      <el-table-column label="操作" fixed="right" min-width="170" align="center">
        <template slot-scope="scope">
          <el-button size="small" type="text" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="small" type="text" @click="handleDetail(scope.$index, scope.row)">详情</el-button>
        </template>

      </el-table-column>
    </el-table>
    <!--分页工具-->
    <el-pagination
      background
      @size-change="handleSizeChange"
      :current-page="page"
      @current-change="handleCurrentChange"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="limit"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>


    <!--团队界面-->
    <el-dialog
      :title="textMap[dialogStatus]"
      customClass="dialog-width"
       :visible.sync="dialogFormVisible"
      append-to-body
       :close-on-click-modal="false">
      <el-form :model="editForm" label-width="90px" :rules="editFormRules" ref="editForm">
        <el-row >
          <el-col :span="6" style="margin: 0px">
          <el-form-item label="赛事名称" prop="competitionName" style="width: 235px">
            <el-select v-model="competitionName" :disabled="dialogStatus == 'detail'" filterable placeholder="请选择赛事名称">
              <el-option
                v-for="item in projectList"
                :key="item.name"
                :label="item.name"
                :value="item.name">
              </el-option>
            </el-select>
          </el-form-item>
          </el-col>
          <el-col :span="6">
          <el-tooltip class="item" effect="dark" content="请先选择赛事名称，并选择对应的项目编号" placement="top">
              <el-form-item label="项目编号" prop="projectId" style="width: 230px">
                <el-select v-model="editForm.projectId" :disabled="dialogStatus == 'detail'" filterable placeholder="请选择项目编号">
                  <el-option
                    v-for="item in projectData"
                    :key="item.projectId"
                    :label="item.projectId"
                    :value="item.projectId + ''">
                  </el-option>
                </el-select>
              </el-form-item>
          </el-tooltip>
          </el-col>

          <el-col :span="7">
              <el-form-item label="团队名称" prop="teamName" style="width: 230px;">
                  <el-input v-model="editForm.teamName" :disabled="dialogStatus == 'detail'" auto-complete="off" placeholder="请输入团队名称"></el-input>
              </el-form-item>
          </el-col>
            <el-col :span="4">
                <el-button type="primary" style="margin-left: 8px;width: 110px" v-show="dialogStatus != 'detail'" @click="handleAddTeam">添加团队成员</el-button>
            </el-col>
        </el-row>
        <el-table :data="memberData" highlight-current-row  style="width: 100%;">
          <el-table-column type="index" width="30">
          </el-table-column>
          <!--<el-table-column prop="teamNo" label="团队编号" min-width="120">
          </el-table-column>-->
          <el-table-column prop="studentNo" label="学生学号" min-width="80">
          </el-table-column>
          <el-table-column prop="studentName" label="学生姓名" min-width="80">
          </el-table-column>
          <el-table-column prop="collegeName" label="所属学院" min-width="120">
          </el-table-column>
          <el-table-column prop="className" label="班级名称" min-width="120">
          </el-table-column>
          <el-table-column prop="grade" label="年级" min-width="100">
          </el-table-column>
          <el-table-column prop="major" label="专业" min-width="100">
          </el-table-column>
          <el-table-column prop="mail" label="邮箱" min-width="120">
          </el-table-column>
          <el-table-column prop="mobileNumber" label="手机号码" min-width="120">
          </el-table-column>
          <el-table-column
            fixed="right"
            label="操作"
            width="180"
            v-if="dialogStatus != 'detail'">
            <template slot-scope="scope" v-show="dialogStatus != 'detail'" >
              <el-button size="small" v-show="dialogStatus != 'detail'" @click="memberEdit(scope.$index, scope.row)">编辑</el-button>
              <el-button type="danger" v-show="dialogStatus != 'detail'" size="small" @click="memberDel(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" v-show="dialogStatus == 'add'" @click="teamSave">添 加</el-button>
        <el-button type="primary" v-show="dialogStatus == 'update'" @click="teamUpdate">修 改</el-button>
      </div>
    </el-dialog>

      <!--  团队成员-->
      <el-dialog
      customClass="teamDialogClass"
      :title="MemberMap[memberStatus]"
      :visible.sync="innerVisible">
          <el-form :model="member" label-width="80px" :rules="memberRules" ref="member">
              <el-row>
                  <el-col :span="12">
                      <el-form-item label="学号" prop="studentNo">
                          <el-input v-model="member.studentNo" :disabled="memberStatus == 'detail'" auto-complete="off" style="width: 220px;"></el-input>
                      </el-form-item>
                      <el-form-item label="学生姓名" prop="studentName">
                          <el-input  v-model="member.studentName" :disabled="memberStatus == 'detail'" auto-complete="off" style="width: 220px;"></el-input>
                      </el-form-item>
                      <el-form-item label="所属学院" prop="collegeName">
                          <el-input v-model="member.collegeName" :disabled="memberStatus == 'detail'" disabledauto-complete="off" style="width: 220px;"></el-input>
                      </el-form-item>
                      <el-form-item label="班级名称" prop="className">
                          <el-input  v-model="member.className" :disabled="memberStatus == 'detail'" auto-complete="off" style="width: 220px;"></el-input>
                      </el-form-item>
                  </el-col>

                  <el-col :span="7">
                      <el-form-item label="年级" prop="grade">
                          <el-input v-model="member.grade" :disabled="memberStatus == 'detail'" auto-complete="off" style="width: 220px;"></el-input>
                      </el-form-item>
                      <el-form-item label="专业" prop="major">
                          <el-input v-model="member.major" :disabled="memberStatus == 'detail'" auto-complete="off" style="width: 220px;"></el-input>
                      </el-form-item>
                      <el-form-item label="邮箱" prop="mail">
                          <el-input v-model="member.mail" :disabled="memberStatus == 'detail'" auto-complete="off" style="width: 220px;"></el-input>
                      </el-form-item>
                      <el-form-item label="手机号码" prop="mobileNumber">
                          <el-input v-model="member.mobileNumber" type="number" :disabled="memberStatus == 'detail'" auto-complete="off" style="width: 220px;"></el-input>
                      </el-form-item>
                  </el-col>
              </el-row>
          </el-form>

          <div slot="footer" class="dialog-footer">
              <el-button @click="innerVisible = false">取 消</el-button>
              <el-button type="primary" v-show="memberStatus == 'add'"  @click="addMember">添 加</el-button>
              <el-button type="primary" v-show="memberStatus == 'update'"  @click="editMember">修 改</el-button>
          </div>
      </el-dialog>

  </section>
</template>

<script>

    export default {
      data(){
        return{
          teamData:[],   // 通过后台获取的团队数据
          memberList:[], // 添加的团队成员信息
          projectList:[],  // 通过审核的项目信息
          memberData:[],  // 团队成员信息存储
          memberIndex:0,   // 当前选中团队成员的索引
          member:{        // 单个团队成员信息
            teamNo:"",
            studentNo:"",
            studentName:"",
            collegeName:"",
            className:"",
            grade:"",
            major:"",
            mail:"",
            mobileNumber:"",
          },
          total: 0,
          page: 1,  // 当前页
          limit: 10,  // 每页数量
          projectData: [],  // 存储项目信息
          competitionName:"", // 选择的赛事名称
          sels: [], // 列表选中列
          filters: {
            name: ''
          },
          dialogStatus:"",
          memberStatus:"",
          dialogFormVisible: false,
          innerVisible:false,
          textMap: {
            update: '团队信息修改',
            add: '添加团队',
            detail: "团队详情",
            // examine: "项目立项审核",
          },
            MemberMap: {
                update: '团队成员信息修改',
                add: '添加团队成员信息',
                detail: "团队成员详情",
            },
          // 编辑界面数据
          editForm: {
            title:"",
            projectId:"",
            teamNo:"",
            teamName:"",
            enrollTime:"",
              memberList: {
                  memberNo: "",
                  studentNo: "",
                  studentName: "",
                  collegeName: "",
                  className: "",
                  grade: "",
                  major: "",
                  mail: "",
                  mobileNumber: "",
              },
          },
          // 数据校验
          editFormRules: {
            // title: [{required: true, message: '请选择赛事名称', trigger: 'blur'}],
            // competitionName: [{required: true, message: '请选择赛事名称', trigger: 'blur'}],
            // enrollTime: [{required: true, message: '请选择注册日期', trigger: 'blur'}],
            teamName:[{required: true, message: '请输入团队项目', trigger: 'blur'}],
            projectId: [{required: true, message: '请输入项目编号', trigger: 'blur'}],
            teamNo: [{required: true, message: '请输入团队编号', trigger: 'blur'}],
          },
          memberRules:{
            studentNo: [{required: true, message: '请输入学生学号', trigger: 'blur'}],
            studentName: [{required: true, message: '请输入学生姓名', trigger: 'blur'}],
            className: [{required: true, message: '请输入班级名称', trigger: 'blur'}],
            collegeName: [{required: true, message: '请输入所属学院', trigger: 'blur'}],
            grade: [{required: true, message: '请输入年级', trigger: 'blur'}],
            major: [{required: true, message: '请输入专业', trigger: 'blur'}],
            mail: [{required: true, message: '请输入邮箱', trigger: 'blur'}],
            mobileNumber: [{required: true, message: '请输入手机号码', trigger: 'blur'}],
          },
        }

      },
      watch:{
        // 监听选中的赛事名称
        competitionName(value) {
            // this.editForm.projectId = "";
          this.projectData = [];
          this.projectList.forEach((obj) => {
            if (obj.name == value) {
              this.projectData.push(obj);

            }
          });

        },
      },
      mounted(){
       this.getTeam();
       this.getProject();
      },
      methods:{
        // 查询团队信息
        getTeam: function () {
          let teacher = localStorage.getItem("teacherId");
          if (teacher === 'undefined' || teacher === 'null' || teacher === undefined || teacher === null){
            teacher = "";
          }
          var _this = this;
          this.http({
            url: "team/list",
            method: "post",
            data: {
              title: this.filters.name,
              page: this.page,
              limit: this.limit,
              teacherId: teacher,
            },
          }).then(res => {
            _this.teamData = res.data.data.list;
            // _this.memberList = _this.teamData.memberList;
            _this.total = res.data.data.total;
          });
        },

        // 查询项目立项信息
        getProject: function () {
          let teacherId = localStorage.getItem("teacherId");
          // 判断当前用户是否是教师
          if (teacherId === 'undefined' || teacherId === 'null' || teacherId === undefined || teacherId === null){
            teacherId = "";
          }
          var _this = this;
          let params = {
            status:"3",
            name: this.filters.name,
            page: this.page,
            limit: this.limit,
            teacherId:teacherId,
          }

          _this.http.get("project/list", {params:params}).then(res =>{
            _this.projectList = res.data.data.list;
          }).catch(error => {
            console.log("error->", error)
          })
        },
        // 保存or更新成员信息
        teamSave(){
          console.log("editForm--->", this.editForm)
          this.$refs.editForm.validate(valid => {
            if (valid) {
              this.$confirm('确认添加吗？', '提示', {})
                .then(() => {
                  if (this.memberData != "" && this.memberData.length != 0) {
                    // const para = Object.assign({}, this.editForm)
                    // if (this.dialogStatus === "update") {
                    //   saveFlag = '1';
                    // }
                    this.editForm.enrollTime = new Date();
                      let teacher = localStorage.getItem("teacherId");
                      // 判断当前用户是否是教师
                      if (teacher === 'undefined' || teacher === 'null' || teacher === undefined || teacher === null){
                          teacher = "";
                      }
                    let _this = this;
                    this.http({
                      url: "team/add",
                      data: {
                        title: this.competitionName,
                        projectId: this.editForm.projectId,
                        teamNo: this.editForm.teamNo,
                        teamName:_this.editForm.teamName,
                        enrollTime: this.editForm.enrollTime,
                        teacherId:teacher,
                        memberList:this.memberData,
                      },
                      method: "post",
                    }).then(function (res) {
                        _this.dialogFormVisible = false
                      if (res.data.success === true) {// 保存成功
                        _this.memberData.forEach((obj) => {
                          obj.teamNo = res.data.teamNo;
                        });
                        _this.getTeam()
                      } else {  // 保存失败
                        _this.$message.error(res.data.message)
                      }
                    }).catch(error => {
                        _this.dialogFormVisible = false
                        _this.$message.error("添加失败：" + error)
                    });

                  }else {
                    _this.$message({
                      message: "请先添加团队成员",
                      type: 'error'
                    });
                  }

                });
            }
          });
        },
        // 修改
        teamUpdate(){
          this.$refs.editForm.validate(valid => {
              if (valid) {
                  this.$confirm('确认修改吗？', '提示', {})
                      .then(() => {
                          if (this.memberData != "" && this.memberData.length != 0) {
                              this.editForm.enrollTime = new Date();
                              let teacher = localStorage.getItem("teacherId");
                              // 判断当前用户是否是教师
                              if (teacher === 'undefined' || teacher === 'null' || teacher === undefined || teacher === null){
                                  teacher = "";
                              }
                              let _this = this;
                              this.http({
                                  url: "team/update",
                                  data: {
                                      title: this.competitionName,
                                      projectId: this.editForm.projectId,
                                      teamNo: this.editForm.teamNo,
                                      teamName:_this.editForm.teamName,
                                      enrollTime: this.editForm.enrollTime,
                                      teacherId:teacher,
                                      memberList:this.memberData,
                                  },
                                  method: "post",
                              }).then(function (res) {
                                  _this.dialogFormVisible = false
                                  if (res.data.success === true) {// 保存成功
                                      _this.memberData.forEach((obj) => {
                                          obj.teamNo = res.data.teamNo;
                                      });
                                      _this.getTeam()
                                  } else {  // 保存失败
                                      _this.$message.error(res.data.message)
                                  }
                              }).catch(error => {
                                  _this.dialogFormVisible = false
                                  _this.$message.error("修改失败：" + error)
                              });

                          }else {
                              _this.$message({
                                  message: "请先添加团队成员",
                                  type: 'error'
                              });
                          }

                      });
              }
          });
        },
        // 添加团队成员
        addMember(){
          this.$refs.member.validate(valid => {
            if (valid) {
              this.$confirm('确认添加吗？', '提示', {})
                .then(() => {
                  this.memberData.push(this.member);
                  this.innerVisible = false;
                });
            }
          }).catch(() => { })
        },
        // 显示新增界面
        handleAdd: function () {
          this.dialogStatus = 'add'
          this.dialogFormVisible = true;
          // 置空
          this.memberData = [];
          this.editForm = {};
          this.competitionName = ""
        },
        handleAddTeam(){
          if (this.editForm.projectId === null || this.editForm.projectId === undefined || this.editForm.projectId === ""){
            this.$message.warning("请选择赛事名称");
            return;
          }
          let flag = true;
          console.log("list-->", this.projectList)
          this.projectList.forEach((obj)=>{

              console.log(obj.projectId + "obj--->", this.editForm.projectId)

              // TODO 未解决 修改时单人制比赛可以添加成员 bug 查询项目列表方式错误（应该是查询申请的而不是已经通过了的）
              if (obj.projectId == this.editForm.projectId){// 这里不能用===
                  if (obj.format === "1" && this.memberData.length >= 1){
                      this.$message.warning("对不起不能再添加成员！该赛事是单人制")
                      flag = false
                      return;
                  }
              }
          })
            if (! flag){
                return;
            }
          this.memberStatus = "add";
          this.innerVisible = true;
          this.member = {};
        },
        // 显示编辑界面
        handleEdit(index, row) {
          this.memberData = [];
          this.dialogStatus = 'update'
          this.dialogFormVisible = true;

          this.memberData = this.teamData[index].memberList;
          this.competitionName = row.title;
          this.editForm = Object.assign({}, row)
            console.log("editForm--->", this.editForm)
        },
        // 显示详情框
        handleDetail(index, row){
          this.dialogStatus = 'detail';
          this.dialogFormVisible = true;
          this.memberData = [];
          this.memberData = this.teamData[index].memberList;

          this.competitionName = row.title;
          this.editForm = Object.assign({}, row);
        },
        // 显示成员编辑界面
        memberEdit(index, row) {
          this.memberStatus = 'update'
          this.innerVisible = true;
          this.member = row;

          this.memberIndex = index;
          // this.editForm = Object.assign({}, row);
        },
        // 修改团队成员信息
        editMember(){
          this.memberData[this.memberIndex] = this.member;
          this.innerVisible = false;
        },
        // 全选单选多选
        selsChange(sels) {
          this.sels = sels
        },
        // 跳转到某页
        handleCurrentChange(val) {
          // 获取当前页
          this.page = val;
          // 重新获取数据
          this.getTeam();
        },
        // 改变每页条数
        handleSizeChange(val){
          this.limit = val;
          this.getTeam();
        },
        // 删除团队成员信息
        memberDel(index, row){
            this.$confirm('确认删除选中记录吗？', '提示', {
                type: 'warning'
            }).then(() => {
                if (this.dialogStatus === 'add') {
                    this.memberData.splice(index);
                    this.$message({
                        message: "删除成功",
                        type: 'success'
                    });
                } else if (this.dialogStatus === 'update') {
                    let _this = this;
                    this.http.post("teamMember/delete", row).then(res =>{
                        if (res.data.code === 666) {
                            // _this.getTeam();
                            _this.memberData.splice(index);
                            _this.$message({
                                message: "删除成功",
                                type: 'success'
                            });
                        } else {
                            _this.$message.error(res.data.message)
                        }
                    }).catch(error => {
                        _this.$message.error(error)
                    })
                }
            }).catch(error => {
                this.$message.warning(error)
            })
        },
        // 批量删除
        batchRemove(){
          let _this = this;
          this.$confirm('确认删除选中记录吗？', '提示', {
            type: 'warning'
          }).then(() => {

              let ids = []
              _this.sels.forEach((obj) =>{
                  ids.push(obj.teamNo);
              })
              // let teamNos = _this.sels.forEach((obj)=>{
              //     return obj.teamNo;
              // })
            _this.http.post("team/batchRemove", ids)
            // _this.$axios.post("http://127.0.0.1:8888/subject/team/batchRemove", ids)
                .then(res =>{
                    if (res.data.code === 666) {
                        _this.getTeam();
                        _this.$message({
                            message: "删除成功",
                            type: 'success'
                        });
                    } else {
                        _this.$message.error(res.data.message)
                    }

            }).catch(error => {
                _this.$message.error(error)
            })


              /*_this.$axios({
                url: "http://127.0.0.1:8888/subject/team/batchRemove",
                method: "post",
                data: {
                  ids: JSON.stringify(this.sels)
                },
              }).then(function (res) {
                if (res.data.code === 666) {
                  _this.getTeam();
                  Vue.prototype.$message({
                    message: "删除成功",
                    type: 'success'
                  });
                } else {
                  Vue.prototype.$message({
                    message: "删除失败",
                    type: 'error'
                  });
                }
              });*/

          }).catch(() => {
            console.log("cancel");
          });


        },


      },
    }
</script>

<style>
.dialog-width{
  min-width: 980px;
  min-height: 380px;
}
  .teamDialogClass{
    min-width: 700px;
    min-height: 300px;
  }
</style>
